<?php
declare (strict_types = 1);

namespace app\api\controller;

use app\api\model\User as UserModel;
use think\exception\ValidateException;
use think\Request;
use think\Response;
use think\facade\Validate;
use app\api\validate\User as UserValidate;
use app\api\server\Token as TokenServer;


class User extends Base
{
    /**
     * 显示资源列表
     *
     * @return Response
     */
    public function index(): Response
    {
        //
        $data =  UserModel::field('id,username,password,status')
                        ->page($this->page, $this->pageSize)
                        ->select();
        if($data->isEmpty()) {
            return $this->create([], '无数据', 204);
        } else {
            return $this->create($data, '数据获取成功');
        }
    }

    /**
     * 保存新建的资源
     *
     * @param Request $request
     * @return Response
     */
    public function save(Request $request): Response
    {
        //
        $data = $request->param();
        //验证返回
        try {
            Validate(UserValidate::class)->check($data);
        }catch (ValidateException $exception) {
            return $this->create([], $exception->getError(), 400);
        }

        $data['password'] = sha1('blog_') . md5($data['password']) . md5('_encrypt') . sha1($data['password']);
        $data['password'] = sha1($data['password']);
        $id = UserModel::create($data)->getData('id');
        if(Empty($id)) {
            return $this->create([], '数据保存失败', 204);
        } else {
            return $this->create($id, '数据保存成功');
        }
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return Response
     */
    public function read($id): Response
    {
        if(!Validate::isInteger($id)) {
            return $this->create([], 'id参数不合法', 400);
        }

        $data =  UserModel::field('id,username,password,phone,status')
            ->find($id);
        if(Empty($data)) {
            return $this->create([], '无数据', 204);
        } else {
            return $this->create($data, '数据获取成功');
        }
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param int $id
     * @return Response
     */
    public function update(Request $request, int $id): Response
    {
        //
        if(!Validate::isInteger($id)) {
            return $this->create([], 'id参数不合法', 400);
        }
        return $this->create([], 'update', 204);
    }

    /**
     * 删除指定资源
     *
     * @param int $id
     * @return Response
     */
    public function delete($id): Response
    {
        if(!Validate::isInteger($id)) {
            return $this->create([], 'id参数不合法', 400);
        }
        //删除数据
        try {
            UserModel::find($id)->delete();
            return $this->create([], '数据删除成功', 200);
        } catch (\Error $e) {
            return $this->create([], '数据删除错误', 400);
        }

    }

    public function login(Request  $request) :Response
    {
        $username = $request['username'];
        $passwd = $request['passwd'];
        if (empty($username) || empty($passwd)) {
            return $this->create([], '用户名密码不允许为空', 201);
        }
        $userInfo  = UserModel::where('username',$username)->find();
        if ($userInfo) {
            $passwd = md5Pass($passwd, $userInfo['salt']);
            if ($passwd != $userInfo['password']) {
                return $this->create([], '用户名密码不匹配', 201);
            } else {
                $getToken = $this->token($userInfo);
                //test();
                $userInfo['token'] = $getToken;
                $userInfo->save();
                return $this->create($userInfo, '用户登录成功', 1);
            }
        }
        else
        {
            return $this->create([], '用户名密码不匹配', 2011);
        }
    }
    public function token($user)
    {
        $uid = $user['username']; // 接收生成token字符串 如：123
        $token = (new TokenServer())->signToken($uid);
        //dd($token);
        return $token;
    }

    public function verifyToken(Request  $request)
    {
        $token = $request->param('token');
        if (empty($token)) {
            return $this->create([], 'token不允许为空', 201);
        } else {
            try {
                $res = (new TokenServer())->checkToken($token);
                if ($res['status'] != 200 ){
                    return json(['code'=>999,'msg'=>$res['info'],'data'=>''],400);
                }
                else {
                    return json(['code'=>1,'msg'=>'验证成功','data'=>$res['data']],200);
                }
            } catch (\Exception $e) {
                return $this->create([], 'token验证错误', 201);
            }
            
            
        }
    }

    public function  test(Request $request): Response
    {
        return   $this->create([],'Token功能测试成功');
    }

}
